package com.sinoglobal.ningxia.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bugtags.library.Bugtags;
import com.orhanobut.logger.Logger;
import com.sinoglobal.networkconnections.HttpTools;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.MainActivity;
import com.sinoglobal.ningxia.activity.MyActivity;
import com.sinoglobal.ningxia.activity.MyCollectionActivity;
import com.sinoglobal.ningxia.activity.mymessage.MyMessageActivity;
import com.sinoglobal.ningxia.activity.player.LiveConfigActivity;
import com.sinoglobal.ningxia.activity.portal.PortalEntryActivity;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.activity.vip.PersonalInfoSet;
import com.sinoglobal.ningxia.beans.UserJurisdictionBean;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.frame.IChangeFragment;
import com.sinoglobal.ningxia.utils.BitmapUtiles;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.MyAsyncTask;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.StringUtil;
import com.sinoglobal.ningxia.utils.ToastBuilder;
import com.sinoglobal.sinostore.activity.MyMallActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.zhy.http.okhttp.request.RequestCall;

import net.tsz.afinal.FinalBitmap;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import static com.sinoglobal.ningxia.R.id.ll_my_home;

/**
 * @author limeishu
 * @author XINDZ
 * @createdate 2014-6-17 下午5:11:07
 * @Description: TODO(侧边栏)
 * @updatedate 2017年1月17日16:49:36
 * @Description: 添加直播 并进行权限判读
 */
@SuppressLint("ValidFragment")
public class LeftFragment extends Fragment implements OnClickListener {

    private IChangeFragment ichange;// 变化fragment接口
    // 我的主页,我的收藏，我的活动，我的消息
    private LinearLayout myhome, myCollect, myActivity, myMessage, myShop;
    private View view;
    private ImageView setInfo;// 个人设置
    private ImageView head;//头像
    private TextView nickname;// 昵称
    private FinalBitmap fb;
    private Bitmap defaultPic;
    private Intent intent;
    private String localUrl;
    private String url;// 获取头像的地址
    private LinearLayout tvPortalEntry;// 门户入口
    private LinearLayout tvContacts;// 宁夏会议
    private boolean protalFlag = false;//是否开启宁夏会议
    private boolean protalLiveFlag = false;//是否开启宁夏会议里的我要直播
    private LinearLayout pro_ll;// 根据情况展示是否显示

    private LinearLayout livePublisher;//直播
    private LinearLayout livePlayer;//观看直播
    private LinearLayout llLivePublisher;
    private String userName;//用户的账号
    private RequestCall jurisdictionCall;

    public LeftFragment() {
        IntentFilter filter = new IntentFilter();// 【创建IntentFilter对象 意图过滤器】
        // 监听用户icon和登录状态
        filter.addAction(MContants.BROADCAST_USERICON);
        filter.addAction(MContants.BROADCAST_LOGIN);
        filter.addAction(MContants.BROADCAST_JIFEN);
        FlyApplication.context.registerReceiver(new HeadReceiver(), filter);// 【注册广播，参数为（广播接收器，意图过滤器）】
        defaultPic = BitmapFactory.decodeResource(
                FlyApplication.context.getResources(), R.drawable.icon_my_defaulthead);
        fb = FinalBitmap.create(FlyApplication.context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.left_fragment, container, false);
        init(view);
        EventBus.getDefault().register(this);
        if (FlyApplication.isShowPic
                && !StringUtil.isNullOrEmpty(SharedPreferenceUtil.getString(
                FlyApplication.context, "portrait"))) {
            fb.display(head, SharedPreferenceUtil.getString(
                    FlyApplication.context, "pic"), defaultPic, defaultPic);
        } else {
            head.setImageResource(R.drawable.icon_my_defaulthead);
        }
        setOnClickListener();
        boolean isAutoChecked = SharedPreferenceUtil.getBoolean(FlyApplication.context, "autoLogin");//自动登录
        getLive(isAutoChecked, false);//如果勾选了自动登录就自动获取该用户的直播权限状态
        return view;
    }

    /**
     * @param isAutoChecked
     * @param ischeck
     */
    private void getLive(boolean isAutoChecked, boolean ischeck) {
        if (isAutoChecked) {
            userName = SharedPreferenceUtil.getString(getActivity(), SharedPreferenceUtil.USER_NAME);
            if (!"".equalsIgnoreCase(FlyApplication.userId) && userName != null && !userName.equals("")) {//userId是""表示未登录
                ResultCallback jurisCallback = new ResultCallback(getActivity()) {
                    @Override
                    public void onSuccess(String response) {
                        super.onSuccess(response);
                        try {
                            UserJurisdictionBean userJurisdictionBean = JSON.parseObject(response, UserJurisdictionBean.class);
                            setLiveVisible(userJurisdictionBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Bugtags.sendException(e);
                        }
                    }
                };
                ResultCallback checkCallback = new ResultCallback(getActivity()) {
                    @Override
                    public void onSuccess(String response) {
                        super.onSuccess(response);
                        try {
                            UserJurisdictionBean userJurisdictionBean = JSON.parseObject(response, UserJurisdictionBean.class);
                            int live = userJurisdictionBean.getLive();
                            if (live != 1) {
                                ToastBuilder.getIntance(FlyApplication.context).showToast("您没有直播权限");
                            } else {
    //                            Intent intentLivePub = new Intent(getActivity(), LivePublisherActivity.class);
                                Intent intentLivePub = new Intent(getActivity(), LiveConfigActivity.class);
                                startActivity(intentLivePub);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Bugtags.sendException(e);
                        }
                    }
                };
                jurisdictionCall = RemoteImpl.getInstance().getUserJurisdiction(this, userName);
                if (ischeck) {
                    jurisdictionCall.execute(checkCallback);
                } else {
                    jurisdictionCall.execute(jurisCallback);
                }
            }

        }
    }

    /**
     * 设置直播和会议平台的显示与隐藏
     *
     * @param userJurisdictionBean
     */
    private void setLiveVisible(UserJurisdictionBean userJurisdictionBean) {
        int code = userJurisdictionBean.getCode();
        int live = userJurisdictionBean.getLive();
        String rtmp = userJurisdictionBean.getRtmp();
        if (code == 1) {
            pro_ll.setVisibility(View.VISIBLE);
            SharedPreferenceUtil.saveBoolean(getActivity(), SharedPreferenceUtil.IS_PORTAL_FLAG, true);
        } else {
            pro_ll.setVisibility(View.GONE);
            SharedPreferenceUtil.saveBoolean(getActivity(), SharedPreferenceUtil.IS_PORTAL_FLAG, false);
        }
        if (live == 1) {
            llLivePublisher.setVisibility(View.VISIBLE);
            SharedPreferenceUtil.saveBoolean(getActivity(), SharedPreferenceUtil.IS_LIVE_FLAG, true);
            //保存推流地址 2017年5月9日09:27:46
            SharedPreferenceUtil.saveString(getActivity(), SharedPreferenceUtil.LIVE_LOCATION, rtmp);
        } else {
            llLivePublisher.setVisibility(View.GONE);
            SharedPreferenceUtil.saveBoolean(getActivity(), SharedPreferenceUtil.IS_LIVE_FLAG, false);
        }
    }

    private void setOnClickListener() {
        setInfo.setOnClickListener(this);
        myhome.setOnClickListener(this);
        myCollect.setOnClickListener(this);
        myActivity.setOnClickListener(this);
        myMessage.setOnClickListener(this);
        myShop.setOnClickListener(this);
        head.setOnClickListener(this);
        tvPortalEntry.setOnClickListener(this);
        tvContacts.setOnClickListener(this);
        //视频直播需要请求权限 进行单独处理
        livePublisher.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AndPermission.hasPermission(getActivity(), Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA,Manifest.permission.READ_PHONE_STATE)) {
                    //有相机以及麦克风权限
                    toLivePublisherActivity();
                } else {
                    AndPermission.with(LeftFragment.this)
                            .requestCode(1003)
                            .permission(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA,Manifest.permission.READ_PHONE_STATE)
                            .send();
                }

            }
        });
        livePlayer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //前往播放界面
//                Intent intentLivePlayer = new Intent(getActivity(), LivePlayerActivity.class);
//                startActivity(intentLivePlayer);
            }
        });
    }

    //-------------------------------------------视频直播----------------------------------------------
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，第一个参数是当前Acitivity/Fragment，回调方法写在当前Activity/Framgent。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1003)
    private void getLocationYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        //有相机以及麦克风权限
        toLivePublisherActivity();
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1003)
    private void getLocationNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1003).show();
        }
    }

    /**
     * 前往视频直播Activity
     */
    private void toLivePublisherActivity() {
        getLive(true, true);
    }

    //---------------------------------------------------------------视频直播------------------------------------------
    private void init(View view) {
        head = (ImageView) view.findViewById(R.id.left_head_bg);
        nickname = (TextView) view.findViewById(R.id.tv_nickname);
        setInfo = (ImageView) view.findViewById(R.id.left_setting);
        myCollect = (LinearLayout) view.findViewById(R.id.ll_my_myCollect);
        myActivity = (LinearLayout) view.findViewById(R.id.ll_my_myActivity);
        myMessage = (LinearLayout) view.findViewById(R.id.ll_my_myMessage);
        myShop = (LinearLayout) view.findViewById(R.id.ll_my_myshop);
        pro_ll = (LinearLayout) view.findViewById(R.id.portale_ll);
        tvContacts = (LinearLayout) view.findViewById(R.id.ll_my_portale_contacts);
        tvPortalEntry = (LinearLayout) view.findViewById(R.id.ll_my_portale_ntry);
        myhome = (LinearLayout) view.findViewById(ll_my_home);

        //直播
        livePublisher = (LinearLayout) view.findViewById(R.id.ll_my_portale_live_publisher);
        //观看直播(测试中)
        livePlayer = (LinearLayout) view.findViewById(R.id.ll_my_portale_live_player);
        //显示隐藏我要直播
        llLivePublisher = (LinearLayout) view.findViewById(R.id.ll_live_publisher);
        FlyApplication.userId = SharedPreferenceUtil.getString(getActivity(),
                "id");
        Logger.i("userid:" + FlyApplication.userId);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UserJurisdictionBean userJurisdictionBean) {
        setLiveVisible(userJurisdictionBean);
    }

    @Override
    public void onResume() {
        super.onResume();
        // setJifen();
        protalFlag = SharedPreferenceUtil.getBoolean(FlyApplication.context,
                SharedPreferenceUtil.IS_PORTAL_FLAG);
        protalLiveFlag = SharedPreferenceUtil.getBoolean(FlyApplication.context,
                SharedPreferenceUtil.IS_LIVE_FLAG);
        Logger.i("会议权限:" + protalFlag + "直播权限:" + protalLiveFlag);
        if (!"".equals(FlyApplication.userId)) {// 判断是否登录
            url = SharedPreferenceUtil.getString(FlyApplication.context,
                    "photo");
            localUrl = url;
        }
        if (!protalFlag) {
            pro_ll.setVisibility(View.GONE);
            Logger.i("会议权限隐藏");
        } else {
            Logger.i("会议权限显示");
            pro_ll.setVisibility(View.VISIBLE);
        }
        //控制我要直播的显示隐藏
        if (!protalLiveFlag) {
            Logger.i("直播权限隐藏");
            llLivePublisher.setVisibility(View.GONE);
        } else {
            Logger.i("直播权限显示");
            llLivePublisher.setVisibility(View.VISIBLE);
        }
        ItktLog.i("LeftFragment----onResume");
        if (FlyApplication.isShowPic && !"".equals(FlyApplication.userId)) {
            // loadPhotoImg(FlyApplication.userId);// 加载得到用户的头像地址
            getBitmap(localUrl, head);// 加载并显示头像
            // fb.display(head, SharedPreferenceUtil.getString(getActivity(),
            // "pic"), defaultPic, defaultPic);
            nickname.setText(SharedPreferenceUtil.getString(
                    FlyApplication.context, "nickname"));
        } else {
            head.setImageResource(R.drawable.icon_my_defaulthead);
            nickname.setText("昵称");
        }
    }

    public void setChangeFragmentListener(IChangeFragment ichange) {
        this.ichange = ichange;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_head_bg:
            case R.id.left_setting:// 点击设置个人信息，并判断是否登录
                if (!"".equalsIgnoreCase(FlyApplication.userId)) {
                    intent = new Intent(getActivity(), PersonalInfoSet.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), Login.class);
                    intent.putExtra("activity", "setPerson");
                    startActivity(intent);
                }
                break;
            case R.id.ll_my_home:
//                // 关闭左侧
                ((MainActivity) getActivity()).CloseLeftMenu();

                break;
            case R.id.ll_my_myCollect:
                // 跳转到我的收藏界面
                // if (!isLogin) {
                // intent = new Intent(getActivity(), LoginActivity.class);
                // startActivity(intent);
                // } else {
                if (!"".equalsIgnoreCase(FlyApplication.userId)) {
                    intent = new Intent(getActivity(), MyCollectionActivity.class);
                    FlyUtil.intentForward(getActivity(), intent);
                    ichange.changeFragment(0);
                } else {
                    intent = new Intent(getActivity(), Login.class);
                    startActivity(intent);
                }

                // }
                break;


            case R.id.ll_my_myActivity:
                // 跳转到我的活动界面
                // if (!isLogin) {
                // intent = new Intent(getActivity(), LoginActivity.class);
                // startActivity(intent);
                // } else {
                if (!"".equalsIgnoreCase(FlyApplication.userId)) {
                    intent = new Intent(getActivity(), MyActivity.class);
                    FlyUtil.intentForward(getActivity(), intent);
                    ichange.changeFragment(1);
                } else {
                    intent = new Intent(getActivity(), Login.class);
                    startActivity(intent);
                }

                // }
                break;
            case R.id.ll_my_myMessage:
                intent = new Intent(getActivity(), MyMessageActivity.class);
                FlyUtil.intentForward(getActivity(), intent);
                ichange.changeFragment(2);
                break;
            case R.id.ll_my_myshop:
                // 跳转到我的商城
                if (!"".equalsIgnoreCase(FlyApplication.userId)) {
                    intent = new Intent(getActivity(), MyMallActivity.class);
                    FlyUtil.intentForward(getActivity(), intent);
                    ichange.changeFragment(0);
                } else {
                    intent = new Intent(getActivity(), Login.class);
                    startActivity(intent);
                }
                break;
            // 门户入口
            case R.id.ll_my_portale_ntry:
                if (AndPermission.hasPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                    goProtal(0);
                } else {
                    AndPermission.with(LeftFragment.this)
                            .requestCode(1004)
                            .permission(Manifest.permission.READ_PHONE_STATE)
                            .send();
                }

                break;
            // 通讯录
            case R.id.ll_my_portale_contacts:
                if (AndPermission.hasPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                    goProtal(1);
                } else {
                    AndPermission.with(LeftFragment.this)
                            .requestCode(1005)
                            .permission(Manifest.permission.READ_PHONE_STATE)
                            .send();
                }
                break;


        }

    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1004)
    private void getPhoneStateYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        goProtal(0);
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1004)
    private void getPhoneStateNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1004).show();
        }
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1005)
    private void getPhoneState2Yes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        goProtal(1);
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1005)
    private void getPhoneState2No(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1005).show();
        }
    }

    private void goProtal(int tag) {
        if (EquipmentUtil.checkNetState(getActivity())) {
            intent = new Intent(getActivity(), PortalEntryActivity.class);
            intent.putExtra("tag", tag);
            FlyUtil.intentForward(getActivity(), intent);
        } else {
            ToastBuilder.getIntance(FlyApplication.context).showToast(
                    getString(R.string.no_network));
        }
    }

    public class HeadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {

            if (arg1.getAction().equals(MContants.BROADCAST_LOGIN)) {
                head.setImageResource(R.drawable.icon_my_defaulthead);
                nickname.setText("个人中心");
                return;
            }
            if (arg1.getAction().equals(MContants.BROADCAST_JIFEN)) {
                return;
            }

            Bundle info = arg1.getExtras();
            if (info.get("pic") != null) {
                if (FlyApplication.isShowPic) {
                    // loadPhotoImg(FlyApplication.userId);// 加载得到用户的头像地址
                    getBitmap(localUrl, head);
                } else {
                    head.setImageResource(R.drawable.icon_my_defaulthead);
                }
            }
        }
    }


    private void getBitmap(final String imgUrl, final ImageView iv) {

        MyAsyncTask<Void, Void, Bitmap> asyncTask = new MyAsyncTask<Void, Void, Bitmap>(
                getActivity(), false) {

            @Override
            public Bitmap before(Void... params) throws Exception {
                return BitmapUtiles
                        .getNetBitmap(imgUrl, FlyApplication.context);
            }

            @Override
            public void after(Bitmap result) {
                if (result != null) {
                    FlyApplication.PhotoBitmap = result;
                    iv.setImageBitmap(BitmapUtiles
                            .toRoundBitmap(FlyApplication.PhotoBitmap));
                }

            }

            @Override
            public void exception() {
                // Auto-generated method stub

            }
        };
        asyncTask.execute();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (jurisdictionCall != null) {
            HttpTools.getInstance().httpCancel(jurisdictionCall);
        }
    }
}
